package com.liurong.util;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.liurong.domain.SysUser;
import com.liurong.service.UserService;

/**
 * 自定义登录realm
 * 
 * @author lr
 * 
 */
public class UserRealm extends AuthorizingRealm {
	private Logger logger = Logger.getLogger(UserRealm.class);
	@Autowired
	private UserService userService;

	@Override
	public String getName() {
		return "userRealm";
	}

	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof UsernamePasswordToken;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		logger.info("进入 UserRealm 的认证方法！");
		// 从token中取出用户登录信息
		String userName = (String) token.getPrincipal();
		logger.info("获取的username=" + userName);
		// 拿到userName从数据库中查看
		SysUser user = null;
		try {
			user = userService.queryUserForOne(userName);
		} catch (Exception e) {
			logger.error("查询用户是否存在抛出异常：" + e);
		}
		// 如果数据库不存在该用户
		if (user == null) {
			logger.warn("用户 " + userName + " 不存在！");
			return null;
		}
		// 得到从数据库获取的密码
		String passsword = user.getPassword();
		String slat = user.getSalt();
		
		SimpleAuthenticationInfo simpleAuthenticationInfo = null;
		try {
			simpleAuthenticationInfo = new SimpleAuthenticationInfo(
					user, passsword,ByteSource.Util.bytes(slat) ,this.getName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return simpleAuthenticationInfo;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		// TODO Auto-generated method stub
		return null;
	}

}
